package com.yfqy.app.modules.shoppingcart.serviceimpl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yfqy.app.configure.Idgenerator.SnowflakeIdGenerator;
import com.yfqy.app.domain.entity.ProductSku;
import com.yfqy.app.domain.entity.ProductSpu;
import com.yfqy.app.domain.entity.ProductSpuImages;
import com.yfqy.app.domain.entity.ShoppingCart;
import com.yfqy.app.domain.mapper.ProductSkuMapper;
import com.yfqy.app.domain.mapper.ProductSpuImagesMapper;
import com.yfqy.app.domain.mapper.ProductSpuMapper;
import com.yfqy.app.domain.mapper.ShoppingCartMapper;
import com.yfqy.app.enums.ErrorCode;
import com.yfqy.app.enums.ProductStatus;
import com.yfqy.app.exception.BusinessException;
import com.yfqy.app.modules.product.vo.ProductSkuVO;
import com.yfqy.app.modules.product.vo.ProductSpuVO;
import com.yfqy.app.modules.shoppingcart.dto.AddToCartDTO;
import com.yfqy.app.modules.shoppingcart.dto.CartOperateDTO;
import com.yfqy.app.modules.shoppingcart.service.ShoppingCartService;
import com.yfqy.app.modules.shoppingcart.vo.CartItemVO;
import com.yfqy.app.modules.shoppingcart.vo.CartListVO;
import com.yfqy.app.modules.shoppingcart.vo.CartSummaryVO;
import com.yfqy.app.modules.system.vo.CartSelectStats;
import com.yfqy.app.service.UserService;
import com.yfqy.app.util.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ShoppingCartServiceImpl extends UserService implements ShoppingCartService {

    @Resource
    private ProductSpuMapper productSpuMapper;
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private SnowflakeIdGenerator idGenerator;
    @Resource
    private ProductSpuImagesMapper productSpuImagesMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addToCart(AddToCartDTO dto) {

        Long userId = getUserId();

        // 验证商品信息
        ProductSku productSku = validateProductInfo(dto);

        // 查询或创建购物车项
        ShoppingCart cartItem = findOrCreateCartItem(userId, dto);

        // 计算新数量
        int newQuantity = cartItem.getQuantity() + dto.getQuantity();

        // 验证库存并更新数量
        updateCartQuantity(cartItem, newQuantity, productSku.getStock());

        log.info("购物车添加成功，用户ID: {}, SKU ID: {}, 最终数量: {}",
                userId, dto.getSkuId(), cartItem.getQuantity());

        return ErrorCode.SUCCESS.getMessage();
    }

    /**
     * 验证商品信息
     */
    private ProductSku validateProductInfo(AddToCartDTO dto) {
        // 验证SPU
        ProductSpu productSpu = productSpuMapper.selectByPrimaryKey(dto.getSpuId());
        if (productSpu == null || productSpu.getStatus() != ProductStatus.AVAILABLE.getState()) {
            log.warn("商品不存在或不可用，SPU ID: {}", dto.getSpuId());
            throw new BusinessException(ErrorCode.PRODUCT_NOT_EXIST);
        }

        // 验证SKU
        ProductSku productSku = productSkuMapper.selectByPrimaryKey(dto.getSkuId());
        if (productSku == null) {
            log.warn("商品规格不存在，SKU ID: {}", dto.getSkuId());
            throw new BusinessException(ErrorCode.SKU_NOT_EXIST);
        }
        if (productSku.getStatus() != ProductStatus.AVAILABLE.getState()) {
            log.warn("商品规格不可用，SKU ID: {}, 状态: {}", dto.getSkuId(), productSku.getStatus());
            throw new BusinessException(ErrorCode.SKU_NOT_EXIST.getCode(), "商品规格已下架");
        }
        if (!productSku.getSpuId().equals(dto.getSpuId())) {
            log.warn("商品规格不匹配，SPU ID: {}, SKU SPU ID: {}", dto.getSpuId(), productSku.getSpuId());
            throw new BusinessException(ErrorCode.SKU_SPU_MISMATCH);
        }

        return productSku;
    }

    /**
     * 查找或创建购物车项
     */
    private ShoppingCart findOrCreateCartItem(Long userId, AddToCartDTO dto) {
        ShoppingCart existingCart = shoppingCartMapper.selectByCustomerSkuPurchasedStatus(userId, dto.getSkuId());

        if (existingCart != null) {
            log.debug("购物车已存在相同商品，用户ID: {}, SKU ID: {}, 现有数量: {}",
                    userId, dto.getSkuId(), existingCart.getQuantity());
            return existingCart;
        }

        // 创建新的购物车项
        ShoppingCart newCart = new ShoppingCart();
        newCart.setId(idGenerator.nextId());
        newCart.setCustomerId(userId);
        newCart.setSpuId(dto.getSpuId());
        newCart.setSkuId(dto.getSkuId());
        newCart.setQuantity(0); // 初始为0，后面会加上
        newCart.setSelected(true);

        int insertResult = shoppingCartMapper.insert(newCart);
        if (insertResult != 1) {
            log.error("创建购物车项失败，用户ID: {}, SKU ID: {}", userId, dto.getSkuId());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "添加购物车失败");
        }

        log.debug("创建新购物车项，用户ID: {}, SKU ID: {}", userId, dto.getSkuId());
        return newCart;
    }

    @Override
    public CartListVO getCartList() {
        Long userId = getUserId();

        log.debug("获取购物车列表，用户ID: {}", userId);

        // 查询购物车项
        List<ShoppingCart> cartItems = shoppingCartMapper.selectByCustomer(userId);

        if (CollectionUtils.isEmpty(cartItems)) {
            log.info("用户购物车为空，用户ID: {}", userId);
            return createEmptyCartList();
        }

        // 构建购物车项VO列表
        List<CartItemVO> cartItemVOS = buildCartItemVOS(cartItems);

        // 计算统计信息
        CartSummaryVO summary = calculateCartSummary(cartItemVOS);

        // 构建返回结果
        CartListVO result = new CartListVO();
        result.setItems(cartItemVOS);
        result.setSummary(summary);
        result.setHasInvalidItems(cartItemVOS.stream()
                .anyMatch(item -> !item.getAvailable()));

        log.info("获取购物车列表成功，用户ID: {}, 商品数量: {}, 选中数量: {}",
                userId, cartItemVOS.size(), summary.getSelectedCount());

        return result;
    }

    /**
     * 获取购物车统计信息
     */
    public CartSummaryVO getCartSummary() {
        Long userId = getUserId();

        List<ShoppingCart> cartItems = shoppingCartMapper.selectByCustomer(userId);

        if (CollectionUtils.isEmpty(cartItems)) {
            return createEmptySummary();
        }

        List<CartItemVO> cartItemVOS = buildCartItemVOS(cartItems);
        return calculateCartSummary(cartItemVOS);
    }

    /**
     * 构建购物车项VO列表
     */
    private List<CartItemVO> buildCartItemVOS(List<ShoppingCart> cartItems) {
        // 提取SKU ID列表
        List<Long> skuIds = cartItems.stream()
                .map(ShoppingCart::getSkuId)
                .collect(Collectors.toList());

        // 批量查询SKU信息
        List<ProductSkuVO> skuVOS = productSkuMapper.selectSkuVOsByIds(skuIds);
        Map<Long, ProductSkuVO> skuMap = skuVOS.stream()
                .collect(Collectors.toMap(ProductSkuVO::getId, Function.identity()));

        // 提取SPU ID列表
        List<Long> spuIds = cartItems.stream()
                .map(ShoppingCart::getSpuId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询SPU信息
        List<ProductSpuVO> spuVOS = productSpuMapper.selectSpuVOsByIds(spuIds);
        Map<Long, ProductSpuVO> spuMap = spuVOS.stream()
                .collect(Collectors.toMap(ProductSpuVO::getId, Function.identity()));

        // 批量查询商品图片
        List<ProductSpuImages> spuImages = productSpuImagesMapper.selectMainImagesBySpuIds(spuIds);
        Map<Long, String> imageMap = spuImages.stream()
                .collect(Collectors.toMap(ProductSpuImages::getId,
                        images -> extractFirstImage(images.getMainImages())));

        // 构建购物车项VO
        return cartItems.stream()
                .map(cartItem -> buildCartItemVO(cartItem, skuMap, spuMap, imageMap))
                .collect(Collectors.toList());
    }

    /**
     * 构建单个购物车项VO
     */
    private CartItemVO buildCartItemVO(ShoppingCart cartItem,
                                       Map<Long, ProductSkuVO> skuMap,
                                       Map<Long, ProductSpuVO> spuMap,
                                       Map<Long, String> imageMap) {
        CartItemVO cartItemVO = new CartItemVO();
        cartItemVO.setCartId(cartItem.getId());
        cartItemVO.setSpuId(cartItem.getSpuId());
        cartItemVO.setSkuId(cartItem.getSkuId());
        cartItemVO.setQuantity(cartItem.getQuantity());
        cartItemVO.setSelected(cartItem.getSelected());
        cartItemVO.setLimitQuantity(999); // 最大购买数量限制

        ProductSkuVO sku = skuMap.get(cartItem.getSkuId());
        ProductSpuVO spu = spuMap.get(cartItem.getSpuId());

        if (sku == null || spu == null) {
            // 商品已删除或不存在
            cartItemVO.setAvailable(false);
            cartItemVO.setUnavailableReason("商品已下架");
            return cartItemVO;
        }

        // 设置商品信息
        cartItemVO.setSpuName(spu.getSpuName());
//        cartItemVO.setSpecValues(parseSpecValues(sku.getSpecs()));
        cartItemVO.setSpecValues(sku.getSpecs());
        cartItemVO.setMainImage(imageMap.get(cartItem.getSpuId()));
        cartItemVO.setPrice(sku.getPrice());
        cartItemVO.setOriginalPrice(sku.getMarketPrice());
        cartItemVO.setStock(sku.getStock());
        cartItemVO.setWarnStock(sku.getWarnStock());

        // 检查商品可用性
        boolean isAvailable = checkProductAvailability(spu, sku, cartItem.getQuantity());
        cartItemVO.setAvailable(isAvailable);

        if (!isAvailable) {
            if (spu.getStatus() != ProductStatus.AVAILABLE.getState()) {
                cartItemVO.setUnavailableReason("商品已下架");
            } else if (sku.getStatus() != ProductStatus.AVAILABLE.getState()) {
                cartItemVO.setUnavailableReason("商品规格已下架");
            } else if (sku.getStock() < cartItem.getQuantity()) {
                cartItemVO.setUnavailableReason("库存不足");
            } else {
                cartItemVO.setUnavailableReason("商品不可用");
            }
        }

        return cartItemVO;
    }

    /**
     * 检查商品可用性
     */
    private boolean checkProductAvailability(ProductSpuVO spu, ProductSkuVO sku, Integer quantity) {
        return spu != null && sku != null &&
                spu.getStatus() == ProductStatus.AVAILABLE.getState() &&
                sku.getStatus() == ProductStatus.AVAILABLE.getState() &&
                sku.getStock() >= quantity;
    }

    /**
     * 计算购物车统计信息
     */
    private CartSummaryVO calculateCartSummary(List<CartItemVO> cartItems) {
        CartSummaryVO summary = new CartSummaryVO();

        // 计算选中商品
        List<CartItemVO> selectedItems = cartItems.stream()
                .filter(item -> Boolean.TRUE.equals(item.getSelected()) &&
                        Boolean.TRUE.equals(item.getAvailable()))
                .toList();

        // 选中商品数量
        Integer selectedCount = selectedItems.stream()
                .mapToInt(CartItemVO::getQuantity)
                .sum();
        summary.setSelectedCount(selectedCount);

        // 选中商品总金额
        BigDecimal totalAmount = selectedItems.stream()
                .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        summary.setTotalAmount(totalAmount);

        // 总节省金额
        BigDecimal totalSaveAmount = selectedItems.stream()
                .map(item -> {
                    BigDecimal savePerItem = item.getOriginalPrice().subtract(item.getPrice());
                    return savePerItem.multiply(BigDecimal.valueOf(item.getQuantity()));
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        summary.setTotalSaveAmount(totalSaveAmount.max(BigDecimal.ZERO));

        // 购物车总数量
        Integer totalCount = cartItems.stream()
                .mapToInt(CartItemVO::getQuantity)
                .sum();
        summary.setTotalCount(totalCount);

        // 是否有选中商品
        summary.setHasSelected(!selectedItems.isEmpty());

        return summary;
    }

    /**
     * 解析规格值
     */
    private List<String> parseSpecValues(String specs) {
        if (StringUtils.isBlank(specs)) {
            return Collections.emptyList();
        }
        try {
            // 假设specs是JSON格式：{"颜色":"红色","尺寸":"L"}
            Map<String, String> specMap = JSON.parse(specs, new TypeReference<Map<String, String>>() {
            });
            return new ArrayList<>(specMap.values());
        } catch (Exception e) {
            log.warn("解析商品规格失败: {}", specs, e);
            return Collections.emptyList();
        }
    }

    /**
     * 提取第一张图片
     */
    private String extractFirstImage(String images) {
        if (StringUtils.isBlank(images)) {
            return "";
        }
        String[] imageArray = images.split(",");
        return imageArray.length > 0 ? imageArray[0].trim() : "";
    }

    /**
     * 创建空的购物车列表
     */
    private CartListVO createEmptyCartList() {
        CartListVO result = new CartListVO();
        result.setItems(Collections.emptyList());
        result.setSummary(createEmptySummary());
        result.setHasInvalidItems(false);
        return result;
    }

    /**
     * 创建空的统计信息
     */
    private CartSummaryVO createEmptySummary() {
        CartSummaryVO summary = new CartSummaryVO();
        summary.setSelectedCount(0);
        summary.setTotalAmount(BigDecimal.ZERO);
        summary.setTotalSaveAmount(BigDecimal.ZERO);
        summary.setTotalCount(0);
        summary.setHasSelected(false);
        return summary;
    }

    /**
     * 增加商品数量
     */
    @Override
    public void increase(CartOperateDTO dto) {
        Long userId = getUserId();

        // 验证购物车项
        ShoppingCart cartItem = validateCartItem(userId, dto.getCartId());

        // 获取商品SKU信息
        ProductSku productSku = getValidProductSku(cartItem.getSkuId());

        // 计算新数量
        int newQuantity = cartItem.getQuantity() + 1;

        // 更新数量
        updateCartQuantity(cartItem, newQuantity, productSku.getStock());

        log.info("购物车数量增加成功，用户ID: {}, 购物车ID: {}, SKU ID: {}, 新数量: {}",
                userId, dto.getCartId(), cartItem.getSkuId(), newQuantity);
    }

    /**
     * 减少商品数量
     */
    @Override
    public void decrease(CartOperateDTO dto) {
        Long userId = getUserId();

        // 验证购物车项
        ShoppingCart cartItem = validateCartItem(userId, dto.getCartId());

        // 计算新数量
        int newQuantity = cartItem.getQuantity() - 1;

        if (newQuantity <= 0) {
            // 数量为0，删除购物车项
            deleteCartItem(cartItem.getId());
            log.info("购物车数量减少至0，删除购物车项，用户ID: {}, 购物车ID: {}", userId, dto.getCartId());
        } else {
            // 更新数量
            updateCartQuantity(cartItem, newQuantity, null); // 减少数量不需要检查库存
            log.info("购物车数量减少成功，用户ID: {}, 购物车ID: {}, SKU ID: {}, 新数量: {}",
                    userId, dto.getCartId(), cartItem.getSkuId(), newQuantity);
        }
    }

    @Override
    public void cancel(CartOperateDTO dto) {
        Long userId = getUserId();
        ShoppingCart shoppingCart = validateCartItem(userId, dto.getCartId());

        if (Boolean.FALSE.equals(shoppingCart.getSelected())) {
            log.debug("购物车项已是未选中状态，无需重复操作，购物车ID: {}", dto.getCartId());
            return;
        }

        int updateResult = shoppingCartMapper.updateSelectedStatus(shoppingCart.getId(), (byte) 0);
        if (updateResult != 1) {
            log.error("取消选中购物车项失败，购物车ID: {}", dto.getCartId());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "操作失败");
        }

        log.info("取消选中购物车项成功，用户ID: {}, 购物车ID: {}", userId, dto.getCartId());
    }

    @Override
    public void choose(CartOperateDTO dto) {
        Long userId = getUserId();
        ShoppingCart shoppingCart = validateCartItem(userId, dto.getCartId());

        if (Boolean.TRUE.equals(shoppingCart.getSelected())) {
            log.debug("购物车项已是选中状态，无需重复操作，购物车ID: {}", dto.getCartId());
            return;
        }

        int updateResult = shoppingCartMapper.updateSelectedStatus(shoppingCart.getId(), (byte) 1);
        if (updateResult != 1) {
            log.error("选中购物车项失败，购物车ID: {}", dto.getCartId());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "操作失败");
        }

        log.info("选中购物车项成功，用户ID: {}, 购物车ID: {}", userId, dto.getCartId());
    }

    @Override
    public void toggleAll() {
        Long userId = getUserId();

        // 查询总商品数和已选中商品数
        CartSelectStats stats = shoppingCartMapper.selectCartSelectStats(userId);
        if (stats == null || stats.getTotalCount() == 0) {
            log.info("用户购物车为空，无需操作全选，用户ID: {}", userId);
            return;
        }

        boolean shouldSelectAll = !stats.getTotalCount().equals(stats.getSelectedCount());

        if (shouldSelectAll) {
            // 全选
            int updateCount = shoppingCartMapper.updateAllSelectedStatus(userId, true);
            log.info("全选购物车成功，用户ID: {}, 更新数量: {}", userId, updateCount);
        } else {
            // 取消全选
            int updateCount = shoppingCartMapper.updateAllSelectedStatus(userId, false);
            log.info("取消全选购物车成功，用户ID: {}, 更新数量: {}", userId, updateCount);
        }

    }


    /**
     * 验证购物车项（简化版本）
     */
    private ShoppingCart validateCartItem(Long userId, Long cartId) {
        ShoppingCart cartItem = shoppingCartMapper.selectByIdAndCustomer(cartId, userId);
        if (cartItem == null) {
            log.warn("购物车项不存在，购物车ID: {}, 用户ID: {}", cartId, userId);
            throw new BusinessException(ErrorCode.CART_ITEM_NOT_EXIST);
        }

        if (cartItem.getPurchased()) {
            log.warn("购物车项已购买，无法修改，购物车ID: {}", cartId);
            throw new BusinessException(ErrorCode.CART_ITEM_PURCHASED);
        }

        if (!cartItem.getStatus()) {
            log.warn("购物车项已失效，购物车ID: {}", cartId);
            throw new BusinessException(ErrorCode.CART_ITEM_INVALID);
        }

        return cartItem;
    }

    /**
     * 获取有效的商品SKU
     */
    private ProductSku getValidProductSku(Long skuId) {
        ProductSku productSku = productSkuMapper.selectByPrimaryKey(skuId);
        if (productSku == null) {
            log.warn("商品SKU不存在，SKU ID: {}", skuId);
            throw new BusinessException(ErrorCode.PRODUCT_NOT_EXIST);
        }

        if (productSku.getStatus() != ProductStatus.AVAILABLE.getState()) {
            log.warn("商品SKU不可用，SKU ID: {}, 状态: {}", skuId, productSku.getStatus());
            throw new BusinessException(ErrorCode.PRODUCT_NOT_EXIST);
        }

        return productSku;
    }

    /**
     * 更新购物车数量
     */
    private void updateCartQuantity(ShoppingCart cartItem, int newQuantity, Integer stock) {
        // 验证数量范围
        if (newQuantity < 0 || newQuantity > 999) {
            throw new BusinessException(ErrorCode.BAD_REQUEST.getCode(), "商品数量必须在0-999之间");
        }

        // 验证库存（仅在需要时）
        if (stock != null && newQuantity > stock) {
            log.warn("库存不足，SKU ID: {}, 需求数量: {}, 可用库存: {}",
                    cartItem.getSkuId(), newQuantity, stock);
            throw new BusinessException(ErrorCode.STOCK_NOT_ENOUGH.getCode(),
                    String.format("库存不足，剩余%d件", stock));
        }

        // 更新数据库
        int updateResult = shoppingCartMapper.updateQuantity(cartItem.getId(), newQuantity);
        if (updateResult != 1) {
            log.error("更新购物车数量失败，购物车ID: {}, 新数量: {}", cartItem.getId(), newQuantity);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "更新失败");
        }

        cartItem.setQuantity(newQuantity);
    }

    /**
     * 删除购物车项
     */
    private void deleteCartItem(Long cartId) {
        int deleteResult = shoppingCartMapper.deleteById(cartId);
        if (deleteResult != 1) {
            log.error("删除购物车项失败，购物车ID: {}", cartId);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "删除失败");
        }
    }


}
